package edu.utd.text.game.designer.commands;

import java.util.Scanner;
import java.util.StringTokenizer;

import edu.utd.text.game.designer.controller.DesignerController;
import edu.utd.text.game.domain.areas.Room;
import edu.utd.text.game.domain.exceptions.DuplicateGameObjectException;
import edu.utd.text.game.domain.exceptions.GameObjectNotFoundException;
import edu.utd.text.game.domain.item.GameItem;

public class AddGameItemCommand implements DesignerCommand {
	
	public AddGameItemCommand() {  }
	
	public String execute() {
		//get Room name
		Scanner scanner = new Scanner(System.in);
		System.out.println("Room to add item to: ");
		String roomName = scanner.nextLine().trim();
		Room room = DesignerController.INSTANCE.getGameMap().getRoomByName(roomName);
		if (null == room) 
			{ return "Cannot find room \"" + roomName + "\" in the game map."; }
		
		
		//get GameItem name
		System.out.println("Game item name: ");
		String itemName = scanner.nextLine().trim();
		
		//TODO: This is a little clumsy, might want to rethink how this works.
		//maybe retrieve...() should return null instead of throw exception.
		//that would be more consistent w/ the collections framework.
		try {
			room.retrieveGameItemByName(itemName);
			//if we found a game object already in the room, we can't add it
			return "An item with that name already exists in room: \"" 
					+ room.getRoomName() + "\"."; 
		} catch (GameObjectNotFoundException gonfx) { 
			//We didn't find an item by that name in the room, so keep going 
		}
		
		GameItem itemToAdd = new GameItem(itemName);
		
		//get tags
		System.out.println("Enter tags for this item (space-separated): ");
		String tags = scanner.nextLine();
		
		StringTokenizer tokenizer = new StringTokenizer(tags);
		while (tokenizer.hasMoreTokens()) {
			itemToAdd.addTag(tokenizer.nextToken().trim());
		}
		
		//get GameItem description
		System.out.println("Enter a description of the game item:");
		String description = scanner.nextLine();
		itemToAdd.setDescription(description);
		
		//add GameItem to room
		try {
			room.addGameObject(itemToAdd);
		} catch (DuplicateGameObjectException dgox) {
			return "Adding game item FAILED.  For some reason, a duplicate item was found in this room.";
		}
		
		return "Game item: \"" + itemToAdd.getName() + "\" was successfully added to room: \""
			+ room.getRoomName() + "\".";	
	}
}
